import { createVNode } from 'vue'
import { store } from '@/store/setup'
import { defineStore } from 'pinia'
import { bwUtilsCookie } from '@/utils'

import { BwCacheEnum } from '@/enums/cacheEnum'

import type {
  BwUserStateModel,
  BwUserInfoModel,
  BwUserTenantInfoModel,
} from './model'

import { Modal } from 'ant-design-vue'

import { ExclamationCircleOutlined } from '@ant-design/icons-vue'
import { useOidcStoreWithOut } from '@/tools/oidc'

const useUserStore = defineStore({
  id: 'BwUserStore',
  state: (): BwUserStateModel => ({
    userInfo: null,
    tenantList: null,
    token: null,
  }),
  getters: {
    getUserInfo(): Nullable<BwUserInfoModel> {
      return this.userInfo ?? null
    },
    getTenantList(): Nullable<BwUserTenantInfoModel[]> {
      return this.tenantList ?? null
    },
    getToken(): string {
      return this.token ?? bwUtilsCookie.getCookie(BwCacheEnum.token) ?? ''
    },
    getTenantId(): string | number {
      const tenantId = bwUtilsCookie.getCookie('id') ?? ''
      return tenantId
    },
  },
  actions: {
    setToken(info?: Nullable<string>) {
      this.token = info ? info : ''
      bwUtilsCookie.setCookie(BwCacheEnum.token, info ?? '', { expires: 7 })
    },
    setTenantId(id: string | number) {
      bwUtilsCookie.setCookie('id', id.toString(), { expires: 7 })
    },
    setUserInfo(info: Nullable<BwUserInfoModel>) {
      if (info) {
        bwUtilsCookie.setCookie('userId', info.toString(), { expires: 7 })
      } else {
        bwUtilsCookie.delCookie('userId')
      }
      this.userInfo = info
    },
    setTenantList(listInfo: Nullable<BwUserTenantInfoModel[]>) {
      this.tenantList = listInfo
    },

    removeToken() {
      this.token = null
      bwUtilsCookie.delCookie(BwCacheEnum.token, undefined)
    },

    removeTenantId() {
      bwUtilsCookie.delCookie('id', undefined)
    },

    resetState() {
      this.removeToken()
      this.removeTenantId()
      this.setUserInfo(null)
      this.setTenantList(null)
    },

    /** logout */
    async logout() {
      if (this.getToken) {
        try {
          const oidcStore = useOidcStoreWithOut()
          // const c = oidcStore.oidcRefreshToken()
          // 登出oidc
          await oidcStore.signOutOidc()
        } catch (e) {
          console.error('注销Token失败', e)
        }
      }
      this.resetState()
      this.setToken(null)
      this.setUserInfo(null)
    },

    /**
     * @description: Confirm before logging out
     */
    confirmLoginOut() {
      Modal.confirm({
        title: '注销登录',
        icon: createVNode(ExclamationCircleOutlined),
        content: createVNode(
          'div',
          { style: 'color:red;' },
          '您确定要注销当前登录吗?'
        ),
        onOk: async () => {
          this.logout()
        },
      })
    },
  },
})

// Need to be used outside the setup
export function useUserStoreWithOut() {
  return useUserStore(store)
}
